<template>
  <a-row>
    <a-col :span="24" class="col-padding">
      <a-form layout="inline" :model="formState">

        <a-form-item label="图片URL">
          <a-input v-model:value="formState.imageUrl" placeholder="" />
        </a-form-item>

        <a-form-item>
        <a-upload
          v-model:file-list="fileList"
          name="file"
          list-type="picture"
          :multiple="false"
          @change="handleChange"
          :beforeUpload="beforeUpload"
          >
          <a-button>
            <upload-outlined></upload-outlined>
            选择图片
          </a-button>
        </a-upload>
        </a-form-item>

        <a-form-item label="涂抹文字">
        <a-input v-model:value="formState.words" placeholder="" style="width:400px" />
        </a-form-item>

        <a-form-item label="短边尺寸">
        <a-input v-model:value="formState.compressSize" placeholder="1200" style="width:80px" />
        </a-form-item>

        <a-form-item>
        <a-button type="primary" @click="onSubmit" :loading="ocrState.processing">开始</a-button>
        </a-form-item>
      </a-form>
    </a-col>
  </a-row>
  <a-row class="mt-2">
    <a-col :span="8" class="col-padding" v-if="formState.previewImage" style="backgound-color:#eee;">
      <a-divider>原始图片</a-divider>
      <a-card>
        <a-image
          width="100%"
          v-model:src="formState.previewImage"
          fallback=""
        />
      </a-card>
    </a-col>
    <a-col :span="8" class="col-padding" v-if="ocrState.ocrDone">
      <a-divider>OCR标注</a-divider>
      <a-card>
        <a-image
          width="100%"
          v-model:src="ocrState.ocrImage"
          fallback=""
        />
        <a-divider>识别结果</a-divider>
        <p>
          <a-textarea
            :read-only="true"
            v-model:value="ocrState.ocrText"
            :auto-size="{ minRows: 5, maxRows: 20 }"
          />
        </p>
      </a-card>
    </a-col>
    <a-col :span="8" class="col-padding" v-if="ocrState.mosaicDone">
      <a-divider>涂抹结果</a-divider>
      <a-card>
        <a-image
          width="100%"
          v-model:src="ocrState.mosaicImage"
          fallback=""
        />
        <a-divider>已涂抹的文字</a-divider>
        <p>
          <a-textarea
            :read-only="true"
            v-model:value="ocrState.mosaicMatchedText"
            :auto-size="{ minRows: 5, maxRows: 20 }"
          />
        </p>
        <a-divider>未涂抹的文字</a-divider>
        <p>
          <a-textarea
            :read-only="true"
            v-model:value="ocrState.mosaicNotMatchedText"
            :auto-size="{ minRows: 5, maxRows: 30 }"
          />
        </p>
      </a-card>
    </a-col>
  </a-row>


</template>

<script>


import { UploadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { defineComponent, ref, reactive } from 'vue';
import axios from 'axios'

export default defineComponent({
  components: {
    UploadOutlined,
  },

  setup() {
    const formState = reactive({
      words: ref(''),
      compressSize: ref('1200'),
      previewImage: ref(''),
      imageUrl:ref('')
    });
    const ocrState = reactive({
      ocrDone: ref(false),
      ocrImage: ref(''),
      ocrText: ref(''),
      mosaicDone: ref(false),
      mosaicImage: ref(''),
      mosaicMatchedText: ref(''),
      mosaicNotMatchedText: ref(''),
      processing: ref(false)
    });
    const handleChange = info => {
      
      const status = info.file.status;

      if (status !== 'uploading') {
        console.log(info.file, info.fileList);
      }

      if (status === 'done') {
        message.success(`${info.file.name} file uploaded successfully.`);
      } else if (status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    };
    const onSubmit = () => {
      ocrState.processing = true;
      console.log('submit!');
      const formData = new FormData();
      if(formState.imageUrl){
        formData.append('url', formState.imageUrl)
        formData.append('rt_origin', '1')
      }else{
        formData.append('img', formState.previewImage.replace('data:image/jpeg;base64,',''))
      }
      formData.append('rt_ocr', '1')
      formData.append('rt_mosaic', '1')
      formData.append('shortlen',formState.compressSize)
      if(formState.words){
        formData.append('keyword', formState.words)
      }
      axios.post('api/tr-run/', formData).then(res => {
        // console.log(res);
        ocrState.processing = false;
        const ocr = res.data.data;
        // console.log(ocr);
        if(ocr.ocr_info){
          let ocr_data = [];
          for(let i=0;i<ocr.ocr_info.length;i++){
            ocr_data.push(JSON.stringify(ocr.ocr_info[i]));
          }
          ocrState.ocrDone = true;
          ocrState.ocrText = JSON.stringify(ocr_data, null, 2);          
        }
        if(ocr.ocr_img){
          ocrState.ocrDone = true;
          ocrState.ocrImage = 'data:image/jpeg;base64,'+ocr.ocr_img;
        }
        if(ocr.mosaic_info){
          ocrState.mosaicDone = true;
          ocrState.mosaicMatchedText = JSON.stringify(ocr.mosaic_info.matched_text, null, 2);
          ocrState.mosaicNotMatchedText = JSON.stringify(ocr.mosaic_info.not_matched_text, null, 2);
        }
        if(ocr.mosaic_img){
          ocrState.mosaicDone = true;
          ocrState.mosaicImage = 'data:image/jpeg;base64,'+ocr.mosaic_img;
        }
        if(ocr.origin_img){
          formState.previewImage = 'data:image/jpeg;base64,'+ocr.origin_img;
        }
      }).catch(err => {
        ocrState.processing = false;
        console.error(err);
      })
    };
    const beforeUpload = (file) => {
      // const me = this;
      console.log(file);
      const r = new FileReader();
      r.readAsDataURL(file);
      r.onload = e => {
        formState.previewImage = e.target.result;
      };
      return new Promise((resolve, reject) => {
        return reject(false);
      });
    };
    const getBase64 = (file) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
      })
    };
    const handlePreview = async (file) => {
      console.log(file);
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    }

    return {
      handleChange,
      fileList: ref([]),
      formState,
      onSubmit,
      beforeUpload,
      getBase64,
      handlePreview,
      ocrState
    };
  },
});
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  padding: 5px;
}
.col-padding {
  padding:5px;
}
.mt-2 {
  margin-top:20px;
}
</style>
